import logging
import os
from pathlib import Path

from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.routing import Mount, Route
from starlette.staticfiles import StaticFiles
from starlette_admin import I18nConfig
from starlette_admin.contrib.sqla import Admin, ModelView

from src.config import load_config
from src.infrastructure.db.main import build_sa_engine
from src.infrastructure.db.models import *
from src.infrastructure.logger import configure_logging

from .middleware import DBSessionMiddleware
from .stats import get_stats
from .views import *
from .views.home import HomeView

logger = logging.getLogger(__name__)


def init_admin() -> Starlette:
    config = load_config()
    dir_path = Path(__file__).parent

    configure_logging()

    engine = build_sa_engine(config.db)

    routes = [
        Route("/get_stats", get_stats, methods=["POST"]),
        Mount(
            "/static",
            StaticFiles(directory=os.path.join(dir_path, "static")),
            name="static",
        ),
    ]

    middleware = [Middleware(DBSessionMiddleware, engine=engine)]

    app = Starlette(routes=routes, middleware=middleware)

    admin = Admin(
        engine,
        base_url="/admin",
        title="Admin Dashboard",
        statics_dir=os.path.join(dir_path, "static"),
        templates_dir=os.path.join(dir_path, "templates"),
        index_view=HomeView(label="Home", icon="fa fa-home"),
        i18n_config=I18nConfig(default_locale="ru", language_switcher=["en", "ru"]),
    )

    admin.add_view(ProxyView(Proxy, icon="fa fa-server", label="Proxies"))
    admin.add_view(UserView(User, icon="fa fa-users"))
    admin.add_view(CategoryView(Category, icon="fa fa-tags", label="Categories"))
    admin.add_view(SiteView(Site, icon="fa fa-th-list"))
    admin.add_view(ModelView(ProxyProvider, icon="fa fa-phone"))
    admin.add_view(ServerView(Server, icon="fa fa-cloud"))
    admin.add_view(VPNServerView(VPNServer, icon="fa fa-cloud", label="VPN Server"))
    admin.add_view(ModelView(Country, icon="fa fa-globe", label="Countries"))
    admin.add_view(OrderView(Order, icon="fa fa-shopping-cart"))
    admin.add_view(ModelView(AllowedIP, icon="fa fa-mobile", label="Allowed IPs"))
    admin.add_view(PaymentView(Payment, icon="fa fa-dollar"))
    admin.add_view(ModelView(Statistics, icon="fa fa-bar-chart", label="Statistics"))
    admin.add_view(ModelView(BotSettings, icon="fa fa-gears", label="Bot Settings"))

    admin.mount_to(app)

    return app


# TODO Переместить все это в main
# TODO Раскоментировать эту функцию
# async def run_admin(app: Starlette) -> None:
#     config = uvicorn.Config(
#         app,
#         host="0.0.0.0",
#         port=5005,
#         log_level=logging.INFO,
#         log_config=None,
#     )
#     server = uvicorn.Server(config)
#     logger.info("Running Admin")
#     await server.serve()
